/*中间切换界面*/

/*中间切换页面模仿Android桌面的的Luncher的设计*/
package com.heima.gdcp.zhushu_music;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.Scroller;

import static com.heima.gdcp.zhushu_music.R.styleable.BigDragableLuncher_default_screen;
import static com.heima.gdcp.zhushu_music.R.styleable.DragableLuncher_default_screen;

public class DragableLuncher extends ViewGroup {
    //设置按钮的背景颜色：
    int choseColor ,defaultColor;
    //设置底部按键的的数值：
    ImageButton[] bottomBar;
    //负责获取滑动属性的对象：
    private Scroller mScroller;
    //负责获取滑动功能的速度跟踪器：
    private VelocityTracker mVelocityTracker;
    //滑动的起始X的坐标:
    private int mScrollerX=0;//刚开始默认值为0
    //默认的当前屏幕为第几屏：
    private int mCurrentScreen=0;
    //滚动结束的X坐标:
    private float mLastMotionX;

    private static final int SNAP_VELOCITY = 1000;

    private final static int TOUCH_STATE_REST = 0;
    private final static int TOUCH_STATE_SCROLLING=1;

    private int mTouchState = TOUCH_STATE_REST;

//用户滑动距离的最小值/最小滑动溢出：
    private int mTouchSlop=0;



    public DragableLuncher(Context context) {
        super(context);
        mScroller=new Scroller(context);
        //得到一个用于判定用户是否滑动的距离的临界值：
        mTouchSlop= ViewConfiguration.get(getContext()).getScaledTouchSlop();

        this.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT , LayoutParams.FILL_PARENT));

    }


    public DragableLuncher(Context context, AttributeSet attrs) {
        super(context, attrs);
        mScroller = new Scroller(context);
        mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
        this.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT , LayoutParams.FILL_PARENT));

        //xml中 默认显示第几个view在屏幕中
        TypedArray a = getContext().obtainStyledAttributes(attrs,R.styleable.DragableLuncher);
        mCurrentScreen = a.getInteger(R.styleable.DragableLuncher_default_screen, 0);
        a.recycle();
    }
    //拦截touch事件，返回true继续执行回调函数：
        public boolean onInterceptTouchEvent(MotionEvent ev){
        final int action = ev.getAction();
        if((action==MotionEvent.ACTION_MOVE)&&(mTouchState!=TOUCH_STATE_REST)){
            return true;
        }
        //取得当前的X坐标
            final float x = ev.getX();
            switch (action) {
                case MotionEvent.ACTION_MOVE:
                    //取绝对值
                    final int xDiff = (int) Math.abs(x - mLastMotionX);
                    //若移动的距离小于最小的距离的的话则将移动的标志位置为true，否则为false
                    boolean xMoved = xDiff > mTouchSlop;
                    if (xMoved) {
                        //如果用户沿着X轴滑动足够的距离就滚动
                        mTouchState = TOUCH_STATE_SCROLLING;
                    }
                    break;
                //接触到touch的那一瞬间记录下X坐标:
                case MotionEvent.ACTION_DOWN:
                    //记录下滑动的初始位置:
                    mLastMotionX = x;
                    //如果停止拖动的话：
                    mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING;
                    break;

                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    //向上和中途取消的操作：
                    //停止滑动
                    mTouchState = TOUCH_STATE_REST;
                    break;
            }
            return mTouchState!= TOUCH_STATE_REST;

            }
    //设置是否打开了触摸滑动这一操作：
    //1.默认触摸滑动打开
    public boolean isOpen = true;

    public boolean isOpenTouchAnima(boolean b){
        isOpen = b;
        return isOpen;
    }
    //响应滑动的时间：
    public boolean onTouchEvent(MotionEvent event){
        if (isOpen){
            if (mVelocityTracker==null){
                //如果没有速度探测器就获得一个
                mVelocityTracker = VelocityTracker.obtain();
            }
            //将当前的touch事件添加到探测器里:
            mVelocityTracker.addMovement(event);
            //取得touch事件的类型：
            final int action = event.getAction();
            //取得X轴的坐标:
            final float x = event.getX();
            //处理各种touch事件：
            switch (action) {
                //处理非滑动事件：
                case MotionEvent.ACTION_DOWN:
                    if (!mScroller.isFinished()) {
                        mScroller.abortAnimation();
                    }
                    //记录下初始位置：
                    mLastMotionX = x;
                    break;
                case MotionEvent.ACTION_MOVE:
                    final int deltaX = (int) (mLastMotionX - x);
                    mLastMotionX = x;
                    if (deltaX < 0) {
                        if (mScrollerX > 0) {
                            scrollBy(Math.max(-mScrollerX, deltaX), 0);
                        }
                    } else if (deltaX > 0) {
                        //取得可以滑动的最大距离：
                        final int availableToScroll = getChildAt(getChildCount() - 1).getRight() - mScrollerX - getWidth();
                        if (availableToScroll > 0) {
                            scrollBy(Math.min(availableToScroll, deltaX), 0);
                        }
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    //计算机当前速率：
                    final VelocityTracker velocityTracker = mVelocityTracker;
                    velocityTracker.computeCurrentVelocity(1000);
                    int velocityX = (int) velocityTracker.getXVelocity();

                    if (velocityX > SNAP_VELOCITY && mCurrentScreen > 0) {
                        //滑动到左边的界面
                        snapToScreen(mCurrentScreen - 1);
                    } else if (velocityX < -SNAP_VELOCITY && mCurrentScreen < getChildCount() - 1) {
                        //滑动到右边的界面：
                        snapToScreen(mCurrentScreen + 1);
                    } else {
                        snapToDestination();
                    }
                    if (mVelocityTracker != null) {
                        mVelocityTracker.recycle();
                        mVelocityTracker = null;
                    }
                    mTouchState = TOUCH_STATE_REST;
                    break;
                case MotionEvent.ACTION_CANCEL:
                    mTouchState = TOUCH_STATE_REST;
            }
            mScrollerX = this.getScrollX();
        }
        else {return false;}
        if (bottomBar != null){
            for(int k =0;k<bottomBar.length;k++){
                if (k==mCurrentScreen){
                    bottomBar[k].setBackgroundColor(choseColor);
                }else {
                    bottomBar[k].setBackgroundColor(defaultColor);
                }
            }
        }
                return true;
    }//

    //设置按键的背景颜色的一个构造函数
    public void setBottomBarBg(ImageButton[] imageButton,int choseColor,int defaultColor){
        this.bottomBar = imageButton;
        this.choseColor =choseColor;
        this.defaultColor=defaultColor;
    }

//滑动到判定的界面：
    private void snapToDestination() {
        final int screenWidth = getWidth();
        final int whichScreen = (mScrollerX+(screenWidth/2))/screenWidth;
        snapToScreen(whichScreen);
    }
//带滑动动画效果显示滑动到的页面：
    private void snapToScreen(int whichScreen) {
        mCurrentScreen = whichScreen;
        final int newX = whichScreen*getWidth();
        final int delta = newX-mScrollerX;
        mScroller.startScroll(mScrollerX,0,delta,0,Math.abs(delta)*2);
        invalidate();
    }
//不带动漫效果显示界面面：
    public void setToScreen(int whichScreen){
        mCurrentScreen  = whichScreen;
        final int newX = whichScreen*getWidth();
        mScroller.startScroll(newX,0,0,0,10);
        invalidate();
    }
//当主界面布局改变时调用该函数：
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childLeft=0;
        //获得子元素的个数
        final int count = getChildCount();
        for (int i=0;i<count;i++){
            final View child = getChildAt(i);
            if (child.getVisibility()!=View.GONE){
                final int childWidth = child.getMeasuredWidth();
                child.layout(childLeft,0,childLeft+childWidth,child.getMeasuredHeight());
                childLeft+=childWidth;
            }
        }
    }
    //取得测量到的高和宽：
    protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec){
        super.onMeasure(widthMeasureSpec,heightMeasureSpec);
        //提取出宽度：
        final int width = MeasureSpec.getMode(widthMeasureSpec);
        //提取出宽度的模式：
        final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        if (widthMode!=MeasureSpec.EXACTLY){
            //若不符合，则抛出错误异常
            throw new IllegalStateException("error mode");
        }
        final int heigthMode = MeasureSpec.getMode(heightMeasureSpec);
        if (heigthMode!=MeasureSpec.EXACTLY){
            throw new IllegalStateException("error mode.");
        }

        //子元素将被分配给同样的高宇宽：
        final int count = getChildCount();
        for(int i=0;i<count;i++){
            getChildAt(i).measure(widthMeasureSpec,heightMeasureSpec);
        }
        //滚动到指定的屏幕：
        scrollTo(mCurrentScreen*width,0);
    }
    //计算滚动的坐标：
    public void computeScroll(){
        if (mScroller.computeScrollOffset()){
            mScrollerX = mScroller.getCurrX();
            scrollTo(mScrollerX,0);
            postInvalidate();
        }
    }
}
